from django.db import models
from common.db import BaseModel
from common.utils import build_tree_menu


class Role(BaseModel):
    name = models.CharField(max_length=50, unique=True, verbose_name='角色名称')
    desc = models.CharField(max_length=255, blank=True, null=True, verbose_name='角色描述')
    user = models.ManyToManyField(to='users.UserProfile', related_name='roles', blank=True, verbose_name='用户')

    class Meta:
        db_table = 'role'
        verbose_name = '角色'
        verbose_name_plural = verbose_name

    def menus_list(self):
        return [{'id': menu.id, 'name': menu.name, 'pid': menu.pid.id if menu.pid else None} for menu in
                self.menus.all()]

    def menus_tree_list(self):
        menu_list = [{'id': menu.id, 'name': menu.name, 'level': menu.level, 'path': menu.path, 'scopes': menu.scopes,
                      'is_menu': menu.is_menu, 'pid': menu.pid.id if menu.pid else None, 'children': []} for menu in
                     self.menus.all()]

        return build_tree_menu(menu_list)
